package net.jueb.majong.voice.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.concurrent.Callable;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.async.WebAsyncTask;

import it.sauronsoftware.jave.AudioAttributes;
import net.jueb.majong.core.common.JsonResult;
import net.jueb.majong.voice.util.Config;
import net.jueb.util4j.convert.audio.JaveAudioConvert;

public class AbstractBaseController {

	protected Logger log=LoggerFactory.getLogger(getClass());
	protected WebAsyncTask<JsonResult> buildTask(final JsonResult result)
	{
		Callable<JsonResult> call=new Callable<JsonResult>() {
			@Override
			public JsonResult call() throws Exception {
				return result;
			}
		};
		return buildTask(call);
	}

	protected WebAsyncTask<JsonResult> buildTask(final Callable<JsonResult> async)
	{
		return new WebAsyncTask<JsonResult>(async);
	}

	/**
	 * @param in
	 * @return
	 */
	protected byte[] readAllBytes(InputStream in)throws Exception
	{
		byte[] data=new byte[]{};
		if(in!=null)
		{
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
	        byte[] buffer = new byte[1024];  
	        int len = -1;  
	        while ((len = in.read(buffer)) != -1) {  
	            outSteam.write(buffer, 0, len);  
	        }  
	        outSteam.close();  
	        data=outSteam.toByteArray();  
		}
		return data;
	}
	
	protected byte[] readAllBytesAndClose(InputStream in)throws Exception
	{
		byte[] data=readAllBytes(in);
		in.close();
		return data;
	}
	
	/**
	 * 回复字节数据
	 * @param response
	 * @param data
	 */
	protected void response(HttpServletResponse response,byte[] data)throws Exception
	{
		if(data!=null)
		{
			response.getOutputStream().write(data);
			response.getOutputStream().flush();
			response.getOutputStream().close();
		}
	}

	protected void responseFile(HttpServletResponse response,String fileName,byte[] fileData)
	{
	    try {
	    	fileName = URLEncoder.encode(fileName, "UTF-8");  
		    response.reset();  
		    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
		    response.addHeader("Content-Length", "" + fileData.length);  
		    response.setContentType("application/octet-stream;charset=UTF-8");  
		    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
		    outputStream.write(fileData);  
		    outputStream.flush();  
		    outputStream.close();  
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
	}

	private final JaveAudioConvert jac=new JaveAudioConvert();
	
	protected AudioAttributes getMp3Attrs()
	{
		AudioAttributes audioAttrs=new AudioAttributes();
		audioAttrs.setBitRate(Config.MP3_BitRate); // 设置比特率 
		audioAttrs.setChannels(Config.MP3_Channels); // 设置声音频道 
		audioAttrs.setSamplingRate(Config.MP3_SamplingRate);// 设置节录率 
		audioAttrs.setVolume(Config.MP3_Volume);// 设置音量
		audioAttrs.setCodec("libmp3lame");
		return audioAttrs;
	}
	
	/**
	 * 语音转码
	 * @param sourceFile
	 * @param target
	 * @param format
	 * @param audioAttrs
	 */
	protected void voiceConvert(File sourceFile, File target, String format, AudioAttributes audioAttrs) {
		jac.audioConvert(sourceFile, target,format,audioAttrs);
	}
}
